package org.abc.program.interceptor.admin;

import net.sf.json.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class LoginInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
		Object obj = request.getSession().getAttribute("user");
		String requestURI = request.getRequestURI();
		if (obj == null) {  // 如果没有登录信息
			System.out.println(requestURI + "进入拦截器！");
			String header = request.getHeader("X-Requested-With");
			//判断是否是ajax请求
			if ("XMLHttpRequest".equals(header)) {
				//表示ajax请求
				Map<String, String> map = new HashMap<String, String>();
				map.put("type", "error");
				map.put("msg", "登录会话超时或者还未登录，请重新登录！");
				//以json格式发送到客户端
				response.getWriter().write(JSONObject.fromObject(map).toString());
			}
			//普通链接跳转，直接重定向到登录页面
			response.sendRedirect(request.getServletContext().getContextPath() + "/system/login");
			return false; //等于false就拦截
		}
		return true;  //等于true就放行

	}

	@Override
	public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

	}
}
